package icu.javayanglei.bilibili.config;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;

/**
 * @author yang
 * @version 1.0.0
 * @date 2022-01-16 19:27
 */
public class IdModTableNameParser implements TableNameHandler {
    /**
     * 使用ThreadLocal防止多线程相互影响
     */
    private static final ThreadLocal<Integer> ID = new ThreadLocal<Integer>();
    private final Integer mod;

    IdModTableNameParser(Integer modValue) {
        mod = modValue;
    }

    public static void setId(Integer idValue) {
        ID.set(idValue);
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        Integer idValue = ID.get();
        if (idValue == null) {
            throw new RuntimeException("请设置id值");
        } else {
            String suffix = String.valueOf(idValue % mod);
            //这里清除ThreadLocal的值，防止线程复用出现问题
            ID.set(null);
            return tableName + "_" + suffix;
        }
    }
}
